<?php
/*
 * 地址相关
 */
namespace app\home\controller;

use app\common\controller\IndexBase;
use think\facade\Db;

class Address extends IndexBase
{

    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
    	$uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
        $data = Db::table('user_address')->where('user_id',$uid)->paginate();
		return $this->fetch('',['data'=>$data]);
    }
    //添加
    public function add()
    {
    	$uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect('login.html');
        if ($this->request->isPost()) {
        	$param = $this->request->param();
        	$add = explode(' ',$param['city']);
        	$data = [
        		'user_id'   => $uid,
                'consignee' => $param['name'],
                'mobile' => $param['mobile'],
                'province' => $add[0],
                'city' => $add[1],
                'district' => $add[2],
                'address' => $param['addr']
        	];
        	Db::table('user_address')->insert($data);
        	$this->success('添加成功');
        }
		return $this->fetch('save');
    }
    //编辑
    public function edit()
    {
    	$uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect('login.html');
        if ($this->request->isPost()) {
        	$param = $this->request->param();
        	$add = explode(' ',$param['city']);
        	$data = [
        		'id'   => $param['id'],
        		'user_id'   => $uid,
                'consignee' => $param['name'],
                'mobile' => $param['mobile'],
                'province' => $add[0],
                'city' => $add[1],
                'district' => $add[2],
                'address' => $param['addr']
        	];
        	Db::table('user_address')->update($data);
        	$this->success('修改成功');
        }
        $data = Db::table('user_address')->where(['user_id'=>$uid])->find(input('id'));
		return $this->fetch('save',['data'=>$data]);
    }
    

    
}
